import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
const daoName = "CompClieZhsrmb";
const ButtonGroup = Button.Group;
const columns = [
    { title: '开始日期', width: 120, sorter: true, key: 'SDATE', caption: "SDATE", render: data => datetime.format(data.SDATE, "yyyy-MM-dd"), dispaly: true, filter: true },
    { title: '结束日期', width: 120, sorter: true, key: 'EDATE', caption: "EDATE", render: data => datetime.format(data.EDATE, "yyyy-MM-dd"), dispaly: true, filter: true },
    { title: '存款时点(万元)', width: 140, sorter: true, dataIndex: 'CKSD', key: 'CKSD', dispaly: true, filter: true },
    { title: '存款日均(万元)', width: 140, sorter: true, dataIndex: 'CKRJ', key: 'CKRJ', dispaly: true, filter: true },
    { title: '利润(万元)', width: 130, sorter: true, dataIndex: 'MNLR', key: 'MNLR', dispaly: true, filter: true },
    { title: '中收(万元)', width: 130, sorter: true, dataIndex: 'ZSSR', key: 'ZSSR', dispaly: true, filter: true },
];
const controls = [
    { name: 'SDATE', required: true, type: 'date', dataType:'date', label: '开始日期',  grid: 12 / 24 },
    { name: 'EDATE', required: true, type: 'date', dataType:'date', label: '结束日期', grid: 12 / 24 },
    { name: 'CKSD', required: true, type: 'number', dataType:'number', label: '存款时点(万元)',  grid: 12 / 24 },
    { name: 'CKRJ', required: true, type: 'number', dataType:'number', label: '存款日均(万元)', grid: 12 / 24 },
    { name: 'MNLR', required: true, type: 'number', dataType:'number', label: '利润(万元)',  grid: 12 / 24 },
    { name: 'ZSSR', required: true, type: 'number', dataType:'number', label: '中收(万元)', grid: 12 / 24 },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class CompClieZhsrmbCxForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "ID", permID:this.props.permID }
    });
    this.loadOptionData();
  }
  componentWillReceiveProps(nextProps) {
    const l1 = nextProps.masterSelectedRowKeys.length
    const l2 = this.props.masterSelectedRowKeys.length
    let k1 = -1
    let k2 = -1
    if (l1 > 0) {
      k1 = nextProps.masterSelectedRowKeys[l1 - 1]
    }
    if (l2 > 0) {
      k2 = this.props.masterSelectedRowKeys[l2 - 1]
    }
    if (k1 !== k2) {
      let seeks = [];
      let whereItems = [];
      let WhereCauses = [];
      whereItems.push({
        FieldName: "CUID",
        Operator: "=",
        FieldValues: '' + k1
      })     
      WhereCauses.push({
        WhereItems: whereItems,
        RelationSign: "AND"
      })
      seeks = WhereCauses;
      this.props.dispatch({
        type: `${daoName}/fetch`,
        payload: { daoName, page: 1, pageSize: 10, seeks }
      });
    }
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  showModelHandler(isAdd) {
    let key = null
    if (!isAdd) {
      const len = this.props.selectedRowKeys.length;
      if (len === 0) {
        message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
        return;
      }
      key = this.props.selectedRowKeys[len - 1]
    }
    this.props.dispatch({
      type: `${daoName}/openEdit`,
      payload: { key }
    });
  }
  deleteHandler() {
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择要删除的行！');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要删除选中的${len}行数据吗？`,
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: `${daoName}/remove`,
          payload: { daoName, keys },
        });
      }
    });
  }
  edidOkHandler() {
    const form = this.refs.CompClieZhsrmbCxForm.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        let t = `${daoName}/create`
        const {keyName, record} = this.props;
        let msg = "数据添加成功！"
        if (record[keyName]) {
          values[keyName] = record[keyName];
          t = `${daoName}/patch`
          msg = "数据修改成功！"
        }
        controls.map((c, i) => {
          if (c.type === 'cascader-select') {
            let vs = values[c.name];
            if (vs.length > 0) {
              values[c.name] = vs[vs.length - 1];
            } else {
              values[c.name] = null;
            }
          }
          if (c.dataType === "number") {
            values[c.name] = Number(values[c.name])
          } else if (c.dataType === "date" || c.dataType === "datetime") {
            values[c.name] = !values[c.name] ? null : new Date(values[c.name])
          } else {
            values[c.name] = values[c.name] === undefined ? null : values[c.name]
          }
          if (c.multiple || c.type === 'checkbox-group') {
            values[c.name] = values[c.name].join(',');
          }
        })
        this.state.dataChange = true;
        this.props.dispatch({
          type: t,
          payload: { daoName, values },
        })
      }
    });
  };
  addHandler() {
    const form = this.refs.CompClieZhsrmbCxForm.getForm();
    form.resetFields();
    this.props.dispatch({
      type: `${daoName}/setRecord`,
      payload: { record: {} },
    });
  };
  hideEditHandler() {
    const form = this.refs.CompClieZhsrmbCxForm.getForm();
    form.resetFields();
    if (this.state.dataChange) {
      this.props.dispatch({
        type: `${daoName}/reload`,
        payload: { daoName },
      });
      this.state.dataChange = false;
    }
    this.props.dispatch({
      type: `${daoName}/hideEdit`
    });
  };
  render() {
    let { showEdit, record, offsetHeight, masterSelectedRowKeys, permID } = this.props
    let table2Height = (offsetHeight - 128) * 0.5 - 70
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -10, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}></div>
          <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls} height={table2Height} canExport={false} permID={permID}/>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
  const masterSelectedRowKeys = state['VCompClieKhgl'].selectedRowKeys;
  const { offsetHeight } = state.menus
  return {
    showEdit,
    selectedRowKeys,
    keyName,
    record,
    masterSelectedRowKeys
  }
}
CompClieZhsrmbCxForm = connect(mapStateToProps)(CompClieZhsrmbCxForm)
export default CompClieZhsrmbCxForm;

let render = (props) => React.createElement(CompClieZhsrmbCxForm, props);
let f = new Factory()
f.set("CompClieZhsrmbCxForm", render) 
